
package android.persist.op.sqlite;

import static android.persist.op.sqlite.SQLLogging.SQL_LOG_TAG;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.persist.config.ClassConfig;
import android.persist.op.OrmOperation;
import android.util.Log;

/**
 * An operation to return the ROWID value for a given object. If the object does
 * not exist then null is returned.
 * 
 * @author Richard Schilling
 * @param <OT> the operand type to work on.
 */
public class SQLiteGetRowId<OT> extends OrmOperation<OT, Long> {

    /**
     * The database that this operation is applied against.
     * 
     * @since 1.0
     */
    private final SQLiteDatabase mDatabase;

    /**
     * Class configuration object for {@link operand}'s type.
     * 
     * @since 1.0
     */
    private final ClassConfig<OT> mConfig;

    @SuppressWarnings("unchecked")
    public SQLiteGetRowId(SQLiteDatabase db, OT operand) {
        super(operand);

        mConfig = (ClassConfig<OT>) ClassConfig.getConfig((Class<OT>) operand.getClass());
        mDatabase = db;
    }

    @Override
    public Long call() {

        StringBuilder query = new StringBuilder();
        query.append("SELECT ROWID FROM '");
        query.append(mConfig.storageName);
        query.append("' WHERE ");
        query.append(SQLiteUtil.generateWhere(operand));

        if (Log.isLoggable(SQL_LOG_TAG, Log.DEBUG)) {
            Log.d(SQL_LOG_TAG,
                    query.toString());
        }
        Cursor cursor = mDatabase.rawQuery(query.toString(), null);
        try {
            if (!cursor.moveToFirst()) {
                return null;
            }

            Long result = new Long(cursor.getLong(0));
            return result;

        } finally {
            cursor.close();
        }

    }

}
